/**
 * Created with JetBrains WebStorm.
 * User: kxl
 * Date: 13-11-18
 * Time: 下午1:56
 * To change this template use File | Settings | File Templates.
 */
/*购物车*/
$(function () {
	
    //    顶部搜索
    $("#J_SearchTab li").click(function () {
        var url = $(this).attr("gdata-action");
        $(this).addClass("selected").siblings().removeClass("selected");
        $('#J_TSearchForm').attr("action", url);
    });
    var total = $("#J_Total");
    /*所有订单总价*/
//底部浮动栏效果
    var orderListWrap = $('#J_OrderList');//订单列表；
    var selAll1 = $("#J_SelectAll1");
    var selAll2 = $("#J_SelectAll2");
    //var floatBar_t = $('.J_FloatBar_box').offset().top;
	//var floatNav=$('.J_FloatBar_box1').offset().top;
    autoCartFixed();
	nav_autoCartFixed();
    $(window).scroll(autoCartFixed);
    $(window).resize(autoCartFixed);
	$(window).scroll(nav_autoCartFixed);
    $(window).resize(nav_autoCartFixed);
    function autoCartFixed() {
        var w_w = $(window).height();
        var scroll_top = $(document).scrollTop();
        scroll_top + w_w <= $('.J_FloatBar_box').offset().top ? $('#J_FloatBar').addClass("fixed") : $("#J_FloatBar").removeClass("fixed")
    }
        function nav_autoCartFixed() {

        var scroll_top = $(document).scrollTop();
        scroll_top  >= $('.J_FloatBar_box1').offset().top ? $('#cart-table-th').addClass("nav-fixed") : $("#cart-table-th").removeClass("nav-fixed");
    }
//    订单全选
    (function () {
		
        $('#J_SelectAll1,#J_SelectAll2').click(function () {
            if ($(this).hasClass('selected')) {
                $(this).removeClass("selected");
                selAll1.removeClass("selected");
                selAll2.removeClass("selected");
                $('.J_ItemBody').removeClass("selected");
				 orderListWrap.find(".shop-info").removeClass("selected")
                orderListWrap.find(".order-body").removeClass("all-select")
            } else {
                $(this).addClass("selected");
                selAll1.addClass("selected");
                selAll2.addClass("selected");
              //  $('.J_ItemBody').addClass("selected");
			   orderListWrap.find(".shop-info").addClass("selected")
                orderListWrap.find(".order-body").addClass("all-select")
     
                $(".J_ItemBody").each(function(){                    
                    if($(this).find('.s-checkbox').hasClass('err') == false){
                        $(this).addClass('selected');
                    }
                });

            }
            getTotalFee();
            submit_btnStats();
            selectGoodsNum();
        })
		$('#J_SelectAll1').click(); 
    })();
//    店铺全选
    (function () {
        $(".J_forShop").click(function () {
            var orderBody = $(this).parents(".order-body");
            if (orderBody.hasClass('all-select')) {
                orderBody.removeClass('all-select');
                $(this).parent().removeClass('selected');
                orderBody.find(".item-body").removeClass('selected');
            } else {
                orderBody.addClass('all-select');
                $(this).parent().addClass('selected');              
                orderBody.find(".s-checkbox").each(function(){                    
                    if($(this).hasClass('err') == false){
                        $(this).parents(".item-body").addClass('selected');
                    }
                });
            }
            getTotalFee();
            checkOrderSelect();
            submit_btnStats();
            selectGoodsNum();
        })
    })();
//    单选
    (function () {
        $('.J_CheckBoxItem').click(function () {
            var orderBody = $(this).parents(".order-body");
            var itemBody = $(this).parents(".item-body");
            if (itemBody.hasClass('selected')) {
                itemBody.removeClass("selected");
            } else {
                itemBody.addClass("selected");
            }
            getTotalFee();
            checkitemSelect(orderBody.find(".item-body"));
            checkOrderSelect();
            submit_btnStats();
            selectGoodsNum();
			
        })
    })();
//    检查当前订单列表是否全部选中
    function checkitemSelect(obj) { 
        var flag = true;
        var orderBody = obj.parents(".order-body");
        obj.each(function () {
            if (!$(this).hasClass("selected")) {
                flag = false;
            }
        });
         
        if (!flag) {
            orderBody.removeClass("all-select");
			orderBody.find('.shop-info').removeClass("selected");
        } else {
            orderBody.addClass("all-select");
			orderBody.find('.shop-info').addClass("selected");
        }
    }
    

//    检查所有店铺订单是否选中
    function checkOrderSelect() {
        var flag = true;
        var orderBody = $(".order-body");
        orderBody.each(function () {
            if (!$(this).hasClass("all-select")) {
                flag = false;
            }
        });
        if (!flag) {
            selAll1.removeClass("selected");
            selAll2.removeClass("selected");
        } else {
            selAll1.addClass("selected");
            selAll2.addClass("selected");
        }

    }
    var maxSKU = 10;

    function goodsNum() {
        var plus_btn = $('.J_Plus');//+
        var minus_btn = $('.J_Minus');//--
        var itemAmount = $('.J_ItemAmount');
        var url = "./index.php?app=member/BCart&act=spm&r=alter";
        var num_ipt;
        plus_btn.click(function () {//增1数量
            var obj = {};
            var itemBody = $(this).parents(".item-body");
            obj.goodsId = itemBody.attr("gdata-goodsId");
            obj.recId = itemBody.attr("gdata-recId");
            num_ipt = $(this).prev(".J_ItemAmount");
            var goodsNum = num_ipt.val();
            goodsNum++;
            obj.quantity = goodsNum;
            num_ipt.val(goodsNum);//数量
            $(this).siblings(".J_Minus").removeClass("no-minus").addClass("minus");//显示-
            if (!$(this).hasClass("no-plus")) {
                $.post(url, obj, function (data) {
                    refreshItem(itemBody, data);
                }, "json");
            }
            return false;
        });
        //刷新购物车记录
        function refreshItem(obj, json) {
            var num_ipt=obj.find(".J_ItemAmount");
            if (json.err == 0) {
                for (var _recId in json.data) {
                    var recData = json.data[_recId];
                    var obj = $('div[gdata-recid=' + _recId + ']');
                    obj.find(".item-title").html(recData.goodsName);
                    if (recData.property) {
                        for (var i = 0; i < recData.property.length; i++) {
                            obj.find(".sku-line").eq(i).html(recData.property[i].catName + '：' + recData.property[i].attr);
                        }
                    }
                    obj.find(".price-original").html(toDecimal2(recData.price));
                    obj.find(".price-now").html(toDecimal2(recData.strikePrice));
                    obj.find('.J_ItemSum').html(toDecimal2(recData.total));

                    // recData.price//原价
                    // recData.strikePrice//促销价
                    if (recData.price == recData.strikePrice) {
                        obj.find("div.item-price").find(".price-line:eq(0)").removeClass("price-original").css({"font-weight": "bold"}).siblings().hide();
                        obj.find("div.item-price").find(".price-line:eq(0)").find(".price-original").css({"text-decoration": "none", "font-weight": "bold"})
                    }
                    else {
                        if (obj.find("div.item-price .price-line").length == "1") {
                            obj.find("div.item-price").prepend('<div class="price-line"><em class="price-original">' + recData.price + '</em></div>');
                        }
                        obj.find("div.item-price").find(".price-line:eq(0)").addClass("price-original").css({"font-weight": "normal"}).siblings().show();
                    }
                    //todo:根据原价和折扣价,显示或移除促销标签; recData.price
                    obj.find("div.promo-main span.arrow").attr("gdata-prom-line1", "优惠:" + toDecimal2(recData.price - recData.strikePrice))
                }
                getTotalFee();
            } else {
                var errCode = Number(json.err);
                if (errCode == 1001) {
                    num_ipt.val(json.data);
                    var price=(obj.find(".J_Price").html()*json.data).toFixed(2);
                    obj.find(".J_ItemSum").html(price)//更新价格
                }else if (errCode == 1002) {
                    num_ipt.val(json.data);
                }
                obj.find('.s-checkbox').removeClass('err').show();
                obj.find('.errMsg').hide();
                alert(json.message);
            }
        }
        minus_btn.click(function () {

            var itemBody = $(this).parents(".item-body");
            var obj = {};
            obj.goodsId = itemBody.attr("gdata-goodsId");
            obj.recId = itemBody.attr("gdata-recId");
            var num_ipt = $(this).next(".J_ItemAmount");
            var goodsNum = num_ipt.val();
            $(this).siblings(".plus").removeClass("no-plus");
            if (!$(this).hasClass("no-minus")) {
                goodsNum--;
                if (goodsNum == 1) {
                    $(this).addClass("no-minus").removeClass("minus")
                }
                num_ipt.val(goodsNum);
                obj.quantity = goodsNum;
                $.post(url, obj, function (data) {
                    refreshItem(itemBody, data);
                }, "json");
            }
            return false;
        });
//       手动输入修改商品数量
        itemAmount.keyup(function () {
            var itemBody = $(this).parents(".item-body");
            var obj = {};
            obj.goodsId = itemBody.attr("gdata-goodsId");
            obj.recId = itemBody.attr("gdata-recId");
            var val = $(this).val();
            var reg = /^[1-9]\d*$/;
            if (!reg.test(val) || val == 1) {
                $(this).val(1);
                $(this).prev('.J_Minus').addClass('no-minus').removeClass("minus");
            } else {
                $(this).prev('.J_Minus').removeClass('no-minus');
            }
            obj.quantity = $(this).val();
            $.post(url, obj, function (data) {
             refreshItem(itemBody, data);
             }, "json");
        });
    }
    goodsNum();
// 宝贝图片放大
    function picZoom() {
        $('.img-loaded').hover(function () {
            var picUrl = $(this).find("img").attr("src");
            var offL = $(this).offset().left + 100;
            var offT = $(this).offset().top - 60;
            picUrl = picUrl.replace("88X88", "220X220");
            if ($(".pic_dialog", "body").length) {
                $('.pic_dialog').stop().show().animate({"opacity": 1, "top": offT, "left": offL}, 500
                );
                $('.pic_dialog .pic').attr({"src": picUrl})

            } else {
                var gm_dialog = '<div class="pic_dialog"><div class="contentbox"><div class="item-big-pic cart-pic s240"><a href="" target="_blank" ><img class="pic" src="' + picUrl + '"></a></div><span class="arrow"></span></div></div>';//宝贝图片放大
                $("body").append(gm_dialog);
                $('.pic_dialog').css("opacity", 0).stop().animate({"opacity": 1}, 300).show();
            }
            $('.pic_dialog').css({"top": offT, "left": offL});
        }, function () {
            $('.pic_dialog').css("opacity", 0).hide();
        });
    }

    picZoom();
//    商家促销；
    $('.J_ItemPromotions').hover(function () {
        var l = $(this).offset().left;
        var t = $(this).offset().top + 25;
        var line1 = $(this).find(".arrow").attr("gdata-prom-line1");
        var line2 = $(this).find(".arrow").attr("gdata-prom-line2");
        var tip = '<div class="cart-tips" <div class="ks-contentbox" style="width: 108px;"><div class="promo-d-line">' + line1 + '</div><div class="promo-d-line">' + line2 + '</div><span class="arrow"></span></div>';
        $('body').append(tip);
        $('.cart-tips').css({"left": l, "top": t});
//        $.get("",{},function(){
//
//        }):
    }, function () {
        $('.cart-tips').remove();
    });
//    结算按钮状态
    function submit_btnStats() {
        var flag = false;
        $('.s-checkbox').each(function () {
            if ($(this).parents('.item-body').hasClass("selected") || $(this).parents('.order-body').hasClass("all-select")) {
                flag = true;
            }
        });
        if (flag) {
            $(".submit-btn").removeClass(" submit-btn-disabled");
        } else {
            $(".submit-btn").addClass(" submit-btn-disabled");
        }

    }

//    已选商品数量
    function selectGoodsNum() {
        var i = 0;
        $(".J_CheckBoxItem").each(function () {
            var itemBody = $(this).parents(".item-body");
            if (itemBody.hasClass("selected")) {
                i++;
            }
        });
        $('#J_SelectedItemsCount').html(i)
    }

    //    移入收藏夹
//    请求url = ?app=member/BCart&act=spm&r=move
//        请求类型： post
//    请求数据格式
//    { 'ids':[{ 'goodsId': 商品Id1, ’recId’:记录id1}, { 'goodsId': 商品Id2, ’recId’:记录id2}]}
    function constructO(obj) {
        this.ids = [];
        for (var i = 0; i < obj.length; i++) {
            this.ids[i] = {};
            this.ids[i]["goodsId"] = obj.attr("gdata-goodsId");
            this.ids[i]["recId"] = obj.attr("gdata-recId");
        }
    }

    var favUrl = "./index.php?app=member/BCart&act=spm&r=move";

    function favReq(param, l, t) {
        $.post(favUrl, param, function (data) {
            if (data.err == 0) {
                $('body').append(fav);
                $('.fav-box').css({"left": l, "top": t});
                setTimeout(function () {
                    $('.fav-box').remove();
                }, 400);
            } else if (data.err == 1) {
                alert(data.message);
            }
        }, "json");
    }

    var fav = '<div class="fav-box"><i></i><span class="fav_text">收藏成功"</span></div>';
    $('.J_Fav').click(function () {
        var l = $(this).offset().left;
        var t = $(this).offset().top - 4;
        var orderBody = $(this).parents(".order-body");
        var itemBody = $(this).parents(".item-body");
        var obj = new constructO(itemBody);
        favReq(obj, l, t);
        return false;
    });
    //    批量收藏
    $('.J_BatchFav').click(function () {
        var obj = {};
        obj.ids = [];
        if (checkSelect()) {
            $(".item-body").each(function () {
                if ($(this).hasClass("selected")) {
                    obj.ids.push({"goodsId": $(this).attr("gdata-goodsId"), "recId": $(this).attr("gdata-recId")});
                }
            });
            $.post(favUrl, obj, function (data) {
                if (data.err == 0) {
                    $('.operations').append(fav);
                    setTimeout(function () {
                        $('.fav-box').remove();
                    }, 400)
                } else if (data.err == 1) {
                    alert(data.message)
                }
            }, "json")
        } else {
            alert('请选择宝贝')
        }
        return false;
    });
//    删除订单
    var delUrl = " ./index.php?app=member/BCart&act=spm&r=remove";

    function delReq(param, obj, objparent, len) {

        $.post(delUrl, param, function (data) {
            var objAttr = obj.attr("gdata-goodsid");
            if (data.err == 0) {
                obj.remove();
                if (len == 1) {
                    objparent.remove();
                }
                //头部购物车显示调整
                var _num = $(".item-body").length;
                $(".mc-count").html(_num);

                floatBar_t = $('.J_FloatBar_box').offset().top;
                
                itemLen();
                getTotalFee();
                submit_btnStats();
                selectGoodsNum();
                allItemNum();

            } else if (data.err == 1) {
                alert(data.message);
            }
        }, "json");
    }

    var hightL = '<div class="highlight" style=" width: 988px; height: 99px;"></div>';
    var delURL = "./index.php?app=member/BCart&act=spm&r=remove";
    $('.J_Del').click(function () {
    	
    	var proxy=delCartCallback.apply(this);
    	
    	var currId=$(this).parents(".J_ItemBody").attr("gdata-recid");
        
    	$(".sEnter",".popup_content").attr("index",currId);
    	 showLayer(500,"popup_content_alert","确认删除购物车所选宝贝吗?",proxy);
    	
	    function delCartCallback(){
	    	var that=this;
	    	return function(){
			 var orderBody = $(that).parents(".order-body");
        	 var itemBody = $(that).parents(".item-body");
        	 var itemLen = orderBody.find(".item-body").length+1;
//      	 var l = itemBody.offset().left;
//      	 var t = itemBody.offset().top;
        	 var obj = new constructO(itemBody);
	  		$('body').append(hightL);
//      	 $('.highlight').css({"left": l, "top": t});
        	 delReq(obj, itemBody, orderBody, itemLen);
//      	 $('.highlight').remove();
				if(itemLen==1){
					window.location.reload();
				}
	    	}
	    }
    });
//    { 'ids':[{ 'goodsId': 商品Id1, ’recId’:记录id1}, { 'goodsId': 商品Id2, ’recId’:记录id2}]}
//    批量删除
    $('.J_DeleteSelected').click(function () {
        if (checkSelect()) {
           	showLayer(500,"popup_content_alert","确认删除购物车这些宝贝吗？",function(){
       	 		var obj = {};
	            obj.ids = [];
	            $(".item-body").each(function () {
	                if ($(this).hasClass("selected")) {
	                    obj.ids.push({"goodsId": $(this).attr("gdata-goodsId"), "recId": $(this).attr("gdata-recId")});
	                }
	            });
	            $.post(delURL, obj, function (data) {
	                if (data.err == 0) {
	                    $('.order-body').each(function () {
	                        if ($(this).hasClass("all-select")) {
	                            $(this).remove();
	                        } else {
	                            $(this).find(".item-body").each(function () {
	                                if ($(this).hasClass("selected")) {
	                                    $(this).remove();
	                                }
	                            })
	                        }
	                    });
	                    itemLen();
	                    getTotalFee();
	                    submit_btnStats();
	                    selectGoodsNum();
                        allItemNum();
	                    floatBar_t = $('.J_FloatBar_box').offset().top;
	                    window.location.reload();
	                } else if (data.err == 1) {
	                    alert(data.message)
	                }
	            }, "json");
           })
        } else {
            showLayer(500,"popup_content_noChecked");
            // alert("请选择需要删除的商品")
        }
    });

//结算
    $('.submit-btn').click(function () {
        if(parseInt($('#goodsnum').text()) > 200){
            alert('购物车商品已超200种');
            return false;
        }
        var reqUrl = $(this).attr("href");
        function _postSubmit(url) {
            if($('#sub_form')){
                $('#sub_form').html('').remove();
            }
            var ExportForm = '<form id="sub_form" action="' + url + '" method="post">';
            $('#J_OrderList .selected').each(function () {
				if(!$(this).hasClass('shop-info')){
                ExportForm += '<input type="hidden" value="' + $(this).attr("gdata-recid") + '" name="recid[]" /> ';
				}
            });

            ExportForm += '</form>';
            $('body').append(ExportForm);

            $.post('index.php?app=member/BCart&act=ajaxCheckNum', $('#sub_form').serialize(), function (json) {
                if (json.err == 0) {
                    $('#sub_form').submit();
                } else if (json.err == 1) {
                    
                    var tmpObj,totalNum,totAmount ;
                    if(json.data!=null ){
                        totalNum = Number($('#J_SelectedItemsCount').text());
                        totalAmount = Number($('#J_Total').text());
                        for(x in json.data){
                           
                            tmpObj = $('#d_' + json.data[x].rec_id);
                            tmpObj.find('.td-amount div:last').addClass('errMsg').text('超出库存');
                            tmpObj.find('.s-checkbox').addClass('err').hide();
                            tmpObj.removeClass('selected');
                            totalNum--;
                            totalAmount = totalAmount - Number(json.data[x].price) * Number(json.data[x].need_num);
                        }
                        $('#J_SelectedItemsCount').text(totalNum);
                        $('#J_Total').text(totalAmount.toFixed(2));
                        $('#J_SmallTotal').text(totalAmount.toFixed(2));
                        
                        location.href ='#d_'+json.data[0].rec_id;
                    }
                }
            }, "json");
            //$('#sub_form').submit();
        }

        if (!$(this).hasClass("submit-btn-disabled")) {
            _postSubmit(reqUrl);
        }
        return false;
    });

    function getTotalFee() {
        var fee = 0;
        $('.item-body').each(function () {
            if ($(this).hasClass("selected")) {
                var price = Number($(this).find(".J_ItemSum").html());
                fee += price;
            }
        });
        total.html(toDecimal2(fee));
        $('#J_SmallTotal').html(toDecimal2(fee))
    }

    function toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }

    function checkSelect() {
        var flag = false;
        $('.order-body').each(function () {
            if ($(this).hasClass("all-select")) {
                flag = true;
            }
        });
        $('.item-body').each(function () {
            if ($(this).hasClass("selected")) {
                flag = true;
            }
        });
        return flag
    }

    function itemLen() {
        $('.stats .num').eq(0).html($(".item-body").length);
        var scale = $(".item-body").length / 50;
        $('.bar .normal').width(100 * scale);
    }

    function allItemNum(){
        var itemNum = $('#J_Cart').find(".item-body").length;
        if(itemNum<1){
            itemNum = 0;
        }
        $('#goodsnum').text(itemNum);
    }

    itemLen();

});
